//
//  ApiTarget.swift
//  mac-wky
//
//  Created by Apple on 2018/2/7.
//  Copyright © 2018年 Apple. All rights reserved.
//

import Foundation
import Moya

private let apiAccountUrl = "https://account.onethingpcs.com"
private let apiControlUrl = "https://control.onethingpcs.com"
private let apiRemoteDlUrl = "http://control.remotedl.onethingpcs.com"


struct TaskInfo {
    var name: String
    var url: String
    var filesize: Int
}

enum ApiTarget {
    /// 手机号是否已经注册(注：此方法无效)
    case isRegister(phone: String)
    /// 手机号 + 密码 登录
    case login(phone: String, pwd: String)
    /// 获取设备列表
    case getListPeer(phone: String)
    /// 获取用户信息 sn: 设备device_sn
    case getUserInfo(sn: String)
    /// 获取设备云添加信息 pid: 设备的peerid type下载状态: 0-未完成 1-已经完成
    case getRemoteDlUrlList(pid: String, type: String)
    /// 云添加登陆 pid: 设备的peerid
    case remoteDlLogin(pid: String)
    /// 解析url pid: 设备的peerid url: 下载地址
    case urlResolve(pid: String, url: String)
    /// 创建下载任务
    case createTask(pid: String, infos: [TaskInfo])
}

extension ApiTarget: TargetType {
    var baseURL: URL {
        switch self {
        case .isRegister, .login, .getUserInfo:
            return URL(string: apiAccountUrl)!
        case .getListPeer:
            return URL(string: apiControlUrl)!
        case .getRemoteDlUrlList, .remoteDlLogin, .urlResolve, .createTask:
            return URL(string: apiRemoteDlUrl)!
        }
    }
    
    var path: String {
        switch self {
        case .isRegister:
            return "user/check"
        case .login:
            return "/user/login"
        case .getListPeer:
            return "listPeer"
        case .getUserInfo:
            return "/activate/userinfo"
        case .getRemoteDlUrlList:
            return "/list"
        case .remoteDlLogin:
            return "/login"
        case .urlResolve:
            return "/urlResolve"
        case .createTask:
            return "/createTask"
        }
        
    }
    
    var method: Moya.Method {
        switch self {
        case .isRegister, .login, .getUserInfo, .urlResolve, .createTask:
            return .post
        case .getListPeer, .getRemoteDlUrlList, .remoteDlLogin:
            return .get
        }
    }
    
    var sampleData: Data {
        return "".data(using: .utf8)!
    }
    
    var task: Task {
        switch self {
        case let .isRegister(phone):
            return isRegisterTast(phone)
        case let .login(phone, pwd):
            return loginTask(with: phone, and: pwd)
        case let .getListPeer(phone):
            return getListPeerTask(phone)
        case let .getUserInfo(sn):
            return getUserInfoTask(sn)
        case let .getRemoteDlUrlList(pid, type):
            return getRemoteDlUrlListTask(pid: pid, type: type)
        case let .remoteDlLogin(pid):
            return remoteDlLoginTask(pid)
        case let .urlResolve(pid, url):
            return urlResolveTask(pid: pid, url: url);
        case let .createTask(pid, infos):
            return createTaskTask(pid: pid, infos: infos)
        }
    }
    
    var headers: [String : String]? {
        switch self {
        case .isRegister, .login, .getUserInfo:
            return ["Content-Type": "application/x-www-form-urlencoded",
                    "Cache-Control": "no-cache"]
        case .getListPeer, .getRemoteDlUrlList, .remoteDlLogin:
            return ["Cache-Control": "no-cache"]
        case .urlResolve, .createTask:
            return ["Content-Type": "text/plain"]
        }
    }
}

extension ApiTarget {
    func isRegisterTast(_ phone: String) -> Task {
        let baseParams = ["phone": phone]
        return .requestCompositeData(bodyData: Helper.getParams(baseParams).paramsData,
                                     urlParameters: ["appversion" : appVersion])
    }
    
    func loginTask(with phone: String, and pwd: String) -> Task {
        let baseParams = [
            "account_type"  :   "4",
            "deviceid"      :   App.random(count: 16),
            "imeiid"        :   App.random(count: 15
            ),
            "phone"         :   phone,
            "pwd"           :   pwd,
            ]
        
        return .requestCompositeData(bodyData: Helper.getParams(baseParams).paramsData,
                                     urlParameters: ["appversion" : appVersion])
    }
    
    func getListPeerTask(_ phone: String) -> Task {
        let baseParams = [
            "appversion"    :   appVersion,
            "v"             :   "1",
            "ct"            :   "1"
            ]
        return .requestParameters(parameters: Helper.getParams(baseParams, isGet: true).params,
                                  encoding: URLEncoding.default)
    }
    
    func getUserInfoTask(_ sn: String) -> Task {
        let baseParams = ["sn": sn]
        return .requestCompositeData(bodyData: Helper.getParams(baseParams, isGet: true).paramsData,
                                     urlParameters: ["appversion" : appVersion])
    }
    
    func getRemoteDlUrlListTask(pid: String, type: String) -> Task {
        let baseParams = [
            "pid"           :   pid,
            "v"             :   "2",
            "ct"            :   "32",
            "pos"           :   "0",
            "number"        :   "100",
            "type"          :   type,
            "needUrl"       :   "0"
        ]
        return .requestParameters(parameters: Helper.getParams(baseParams, isGet: true).params,
                                  encoding: URLEncoding.default)
    }
    
    func remoteDlLoginTask(_ pid: String) -> Task {
        let baseParams = [
            "pid"           :   pid,
            "v"             :   "1",
            "ct"            :   "32"
        ]
        return .requestParameters(parameters: Helper.getParams(baseParams, isGet: true).params,
                                  encoding: URLEncoding.default)
    }
    
    func urlResolveTask(pid: String, url: String) -> Task {
        return .requestCompositeParameters(bodyParameters: ["url" : url],
                                           bodyEncoding: JSONEncoding.default,
                                           urlParameters: ["pid" : pid, "v": 1])
    }
    
    func createTaskTask(pid: String, infos: [TaskInfo]) -> Task {
        
        let tasks = infos.map { return ["name": $0.name, "url": $0.url, "filesize": $0.filesize] }

        let baseParams: [String : Any] = ["path": "/media/sda1/onecloud/tddownload", "tasks": tasks]
        
        return .requestCompositeParameters(bodyParameters: baseParams,
                                           bodyEncoding: JSONEncoding.default,
                                           urlParameters: ["pid" : pid, "v": 2, "ct": 32])
    }
}
